import { http } from "@/utils/http";
import { baseUrlApi } from "./utils";

export type UserResult = {
  success: boolean;
  data: {
    /** 头像 */
    avatar: string;
    /** 用户名 */
    username: string;
    /** 昵称 */
    nickname: string;
    /** 当前登录用户的角色 */
    roles: Array<string>;
    /** 按钮级别权限 */
    permissions: Array<string>;
    /** `token` */
    accessToken: string;
    /** 用于调用刷新`accessToken`的接口时所需的`token` */
    refreshToken: string;
    /** `accessToken`的过期时间（格式'xxxx/xx/xx xx:xx:xx'） */
    expires: Date;
  };
};

export type RefreshTokenResult = {
  success: boolean;
  data: {
    /** `token` */
    accessToken: string;
    /** 用于调用刷新`accessToken`的接口时所需的`token` */
    refreshToken: string;
    /** `accessToken`的过期时间（格式'xxxx/xx/xx xx:xx:xx'） */
    expires: Date;
  };
};

/** 登录 */
export const getLogin = (data?: object) => {
  // 暂对返回值进行封装
  return new Promise<UserResult>((resolve, reject) => {
    http
      .request<any>("post", baseUrlApi("/login/account"), { data })
      .then(res => {
        let reqData = res.data;
        // 处理返回值
        let newData = {
          success: true,
          data: {
            avatar: reqData.image,
            username: reqData.name,
            nickname: reqData.name,
            roles: [],
            permissions: [],
            accessToken: reqData.token,
            refreshToken: "",
            expires: new Date("2030-10-30")
          }
        };
        resolve(newData);
      })
      .catch(e => {
        reject(e);
      });
  });
};

/** 刷新`token` */
export const refreshTokenApi = (data?: object) => {
  return http.request<RefreshTokenResult>("post", "/refresh-token", { data });
};

/** 获取门店列表 */
export const loginStoreList = () => {
  return http.request<RefreshTokenResult>(
    "get",
    baseUrlApi("/login/store/list")
  );
};
